﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

namespace ReferenceTemplate.Windows8.Controls
{
    public class OffsetGridView : GridView, INotifyPropertyChanged
    {
        public OffsetGridView()
            : base()
        {
            Loaded += ScrollGridView_Loaded;
        }

        //Hasta que no esté cargado el ScrollGridView no podemos acceder a su ScrollViewer
        void ScrollGridView_Loaded(object sender, RoutedEventArgs e)
        {
            ScrollViewer scrollViewer = GetVisualChild<ScrollViewer>(this);

            if (scrollViewer != null)
            {
                scrollViewer.ViewChanging += sv_ViewChanging;
            }
        }

        void sv_ViewChanging(object sender, ScrollViewerViewChangingEventArgs e)
        {
            ScrollViewer scrollViewer = sender as ScrollViewer;
            if (scrollViewer != null)
            {
                Offset = scrollViewer.HorizontalOffset;
            }
        }

        private double offset;
        public double Offset
        {
            get
            {
                return offset;
            }
            set
            {
                offset = value; OnPropertyChanged("Offset");
            }
        }

        public T GetVisualChild<T>(DependencyObject parent) where T : DependencyObject
        {
            T child = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);

            for (int i = 0; i < numVisuals; i++)
            {
                DependencyObject v = (DependencyObject)VisualTreeHelper.GetChild(parent, i);

                child = v as T;

                if (child == null)
                    child = GetVisualChild<T>(v);
                if (child != null)
                    break;
            }
            return child;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
    }
}
